
package com.jwdf.uda.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

import android.annotation.SuppressLint;

/**
 * 日期操作工具包
 */
@SuppressLint("SimpleDateFormat")
public class DateUtils {
	private static long DAY_TIME = 24 * 60 * 60 * 1000;
    private static Calendar calS=Calendar.getInstance();
    private static Pattern   p   =   Pattern.compile("\\d{4}-\\d{2}-\\d{2}");//定义整则表达式
    
    private final static ThreadLocal<SimpleDateFormat> dateFormater = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };
    private final static ThreadLocal<SimpleDateFormat> dateFormater1 = new ThreadLocal<SimpleDateFormat>() {
    	@Override
    	protected SimpleDateFormat initialValue() {
    		return new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    	}
    };

    private final static ThreadLocal<SimpleDateFormat> dateFormater2 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd");
        }
    };
    private final static ThreadLocal<SimpleDateFormat> dateFormater22 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy.MM.dd");
        }
    };

    private final static ThreadLocal<SimpleDateFormat> dateFormater5 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM");
        }
    };

    private final static ThreadLocal<SimpleDateFormat> dateFormater3 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyyMMddHHmmss");
        }
    };

    private final static ThreadLocal<SimpleDateFormat> dateFormater4 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("dd");
        }
    };

    private final static ThreadLocal<SimpleDateFormat> dateFormater6 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("HHmm");
        }
    };

    private final static ThreadLocal<SimpleDateFormat> dateFormater7 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm");
        }
    };
    private final static ThreadLocal<SimpleDateFormat> dateFormater77 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy.MM.dd HH:mm");
        }
    };
    private final static ThreadLocal<SimpleDateFormat> dateFormater777 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("MM-dd HH:mm");
        }
    };

    private final static ThreadLocal<SimpleDateFormat> dateFormater8 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("M月d日");
        }
    };
    
    private final static ThreadLocal<SimpleDateFormat> dateFormater9 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy年MM月dd日  HH点mm分");
        }
    };
    
    private final static ThreadLocal<SimpleDateFormat> dateFormater99 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("MM月dd日  HH点mm分");
        }
    };
    private final static ThreadLocal<SimpleDateFormat> dateFormater10 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("MM-dd");
        }
    };
    private final static ThreadLocal<SimpleDateFormat> dateFormater110 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("MM月dd日");
        }
    };

    /**
     * 将字符串转为日期类型
     * 
     * @param sdate
     * @return
     */
    public static Date toDate(String sdate) {
        try {
            return dateFormater.get().parse(sdate);
        } catch (ParseException e) {
            return null;
        }
    }

    public static Date toDate2(String sdate) {
        try {
            return dateFormater2.get().parse(sdate);
        } catch (ParseException e) {
            return null;
        }
    }

    public static String getFriendlyTime(int seconds) {
        return getFriendlyTime(1000l*seconds);
    }

    /**
     * 以友好的方式显示时间
     * 
     * @param milliseconds 要比较的时间毫秒数
     * @return 友好的时间显示
     */
    public static String getFriendlyTime(long milliseconds) {
        Date time = new Date(milliseconds);
        String ftime = "";
        Calendar cal = Calendar.getInstance();

        // 判断是否是同一天
        String curDate = dateFormater2.get().format(cal.getTime());
        String paramDate = dateFormater2.get().format(time);
        if (curDate.equals(paramDate)) {
            int hour = (int)((cal.getTimeInMillis() - time.getTime()) / 3600000);
            if (hour <= 0)
                ftime = Math.max((cal.getTimeInMillis() - time.getTime()) / 60000, 1) + "分钟前";
            else
                ftime = hour + "小时前";
            return ftime;
        }

        long lt = time.getTime() / 86400000;
        long ct = cal.getTimeInMillis() / 86400000;
        int days = (int)(ct - lt);
        if (days == 0) {
            int hour = (int)((cal.getTimeInMillis() - time.getTime()) / 3600000);
            if (hour <= 0)
                ftime = Math.max((cal.getTimeInMillis() - time.getTime()) / 60000, 1) + "分钟前";
            else
                ftime = hour + "小时前";
        } else if (days == 1) {
            ftime = "昨天";
        } else if (days == 2) {
            ftime = "前天";
        } else if (days > 2 && days <= 10) {
            ftime = days + "天前";
        } else if (days > 10) {
            ftime = dateFormater2.get().format(time);
        }
        return ftime;
    }

    /**
     * 以友好的方式显示时间
     * 
     * @param sdate
     * @return
     */
    public static String getFriendlyTime(String sdate) {
        Date time = toDate(sdate);
        if (time == null) {
            return "Unknown";
        }
        return getFriendlyTime(time.getTime());
    }

    /**
     * 判断给定字符串时间是否为今日
     * 
     * @param sdate
     * @return boolean
     */
    public static boolean isToday(String sdate) {
        boolean b = false;
        Date time = toDate2(sdate);
        Date today = new Date();
        if (time != null) {
            String nowDate = dateFormater2.get().format(today);
            String timeDate = dateFormater2.get().format(time);
            if (nowDate.equals(timeDate)) {
                b = true;
            }
        }
        return b;
    }

    /**
     * 获取当前时间（格式：yyyy-MM-dd HH:mm:ss）
     * 
     * @return
     */
    public static String getCurrentTime() {
        return dateFormater.get().format(new Date());
    }

    public static String getString(long milliseconds) {
        return dateFormater.get().format(new Date(milliseconds));
    }
    public static String getString1(long milliseconds) {
    	return dateFormater1.get().format(new Date(milliseconds));
    }

    public static String getLastMinute() {
        Calendar calendar = Calendar.getInstance();
        int now = calendar.get(Calendar.MINUTE);
        calendar.set(Calendar.MINUTE, now + 3);
        return dateFormater6.get().format(calendar.getTime());
    }

    public static String getChangeTime(long milliseconds) {
        return dateFormater2.get().format(new Date(milliseconds));
    }
    public static String getChangeTime2(long milliseconds) {
        return dateFormater22.get().format(new Date(milliseconds));
    }
    
    public static String getDataTime(long milliseconds){
        return dateFormater10.get().format(new Date(milliseconds));
    }
    
    /**
     * @param milliseconds 从1970年开始的毫秒数
     * @return 只返回日期，格式"yyyy-MM-dd"
     */
    public static String getDate(long milliseconds) {
        return dateFormater2.get().format(new Date(milliseconds));
    }
    
    public static String getDate2(long milliseconds) {
        return dateFormater22.get().format(new Date(milliseconds));
    }
    
    /**
     * @param milliseconds 从1970年开始的毫秒数
     * @return 只返回日期，格式"yyyy年MM月dd日 hh时mm分"
     */
    public static String getFormatFullDate(long milliseconds) {
        return dateFormater9.get().format(new Date(milliseconds));
    }
    
    /**
     * @param milliseconds 从1970年开始的毫秒数
     * @return 只返回日期，格式"yyyy年MM月dd日 hh时mm分"
     */
    public static String getFormatFullDate9(long milliseconds) {
        return dateFormater99.get().format(new Date(milliseconds));
    }

    /**
     * 获取当前月份和日期(格式：M月d日)
     * 
     * @return
     */
    public static String getMonthAndDate(long milliseconds) {
        return dateFormater8.get().format(new Date(milliseconds));
    }

    /**
     * 获取当前日期(格式：yyyy-MM-dd)
     * 
     * @return
     */
    public static String getCurrentDate() {
        return dateFormater2.get().format(new Date());
    }

    /**
     * 获取昨天日期(格式：yyyy-MM-dd)
     * 
     * @return
     */
    public static String getYesterDate() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, -1);
        return dateFormater2.get().format(cal.getTime());
    }

    /**
     * 获取前天日期(格式：yyyy-MM-dd)
     * 
     * @return
     */
    public static String getBefYesterDate() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, -2);
        return dateFormater2.get().format(cal.getTime());
    }

    /**
     * 获取字符串的日期类型(格式：yyyy-MM-dd)
     * 
     * @return
     */
    public static String getDateToString(Date dt) {
        return dateFormater2.get().format(dt);
    }

    public static String getLongToString(long timeMillis) {
        Date dt = new Date(timeMillis);
        return getDateToString(dt);
    }

    /**
     * 获取Date的日期类型(格式：yyyy-MM-dd)
     * 
     * @return
     */
    public static Date getStringToDate(String time) throws ParseException {
        return dateFormater2.get().parse(time);
    }

    /**
     * 获取当前月份(格式：yyyy-MM)
     * 
     * @return
     */
    public static String getCurrentMonth() {
        return dateFormater5.get().format(new Date());
    }

    /**
     * 获取当前星期一的日期(格式：yyyy-MM-dd)
     * 
     * @return
     */
    public static String getWeekOfFirstDate() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - minusDate(Calendar.DAY_OF_WEEK));
        return dateFormater2.get().format(calendar.getTime());
    }

    // 获取日期间隔间的数组
    private static int minusDate(int dayOfWeek) {
        int minus = 0;
        switch (dayOfWeek) {
            case 1:// 周日
                minus = 6;
                break;
            case 2:// 周一
                minus = 0;
                break;
            case 3:// 周二
                minus = 1;
                break;
            case 4:// 周三
                minus = 2;
                break;
            case 5:// 周四
                minus = 3;
                break;
            case 6:// 周五
                minus = 4;
                break;
            case 7:// 周六
                minus = 5;
                break;
            default:
                break;
        }

        return minus;
    }

    /**
     * 获取当前时间（格式：yyyyMMddHHmmss）
     * 
     * @return
     */
    public static String getSimpleCurrentTime() {
        return dateFormater3.get().format(new Date());
    }

    public static String getSimpleTime(Date dt) {
        return dateFormater4.get().format(dt);
    }

    public static String getSimpleDateTime(long milliseconds) {
        return dateFormater7.get().format(new Date(milliseconds));
    }
    
    public static String getSimpleMinuTime(long milliseconds) {
        return dateFormater77.get().format(new Date(milliseconds));
    }
    
    public static String getSimpleMonthDateTime(long milliseconds) {
        return dateFormater777.get().format(new Date(milliseconds));
    }

    /**
     * 根据开始时间和结束时间返回时间段内的时间集合
     * 
     * @param beginDate
     * @param endDate
     * @return List
     */
    private static List<Date> lDate = new ArrayList<Date>();

    public static List<Date> getDatesBetweenTwoDate(Date beginDate, Date endDate) {
        lDate.clear();
        
        lDate.add(beginDate);// 把开始时间加入集合
        Calendar cal = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        cal.setTime(beginDate);
        boolean bContinue = true;
        while (bContinue) {
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            cal.add(Calendar.DAY_OF_MONTH, 1);
            // 测试此日期是否在指定日期之后
            if (endDate.after(cal.getTime())) {
                lDate.add(cal.getTime());
            } else {
                break;
            }
        }
        lDate.add(endDate);// 把结束时间加入集合
        return lDate;
    }
    
    /**
     * 计算剩余时间
     * @param startDateMillis
     * @param endDateMillis
     * @return
     */
    public static String remainDateToString(long startDateMillis, long endDateMillis){
        Date startDate = new Date(startDateMillis);
        Date endDate= new Date(endDateMillis);
        
        calS.setTime(startDate);
        int startD = calS.get(Calendar.DAY_OF_YEAR);
        int startH = calS.get(Calendar.HOUR_OF_DAY);
        int startMM = calS.get(Calendar.MINUTE);
        
        calS.setTime(endDate);
        int endD = calS.get(Calendar.DAY_OF_YEAR);
        int endH = calS.get(Calendar.HOUR_OF_DAY);
        int endMM = calS.get(Calendar.MINUTE);
        
        
        StringBuilder sBuilder = new StringBuilder();
        if (endDate.compareTo(startDate)<0) {
            return sBuilder.append("已结束").toString();
        }
        int lday = endD-startD;
        int lhour = endH - startH;
        int lminute = endMM - startMM;
        if (lday >0 ) {
            sBuilder.append(lday).append("天");
        }
        if(lhour > 0){
            sBuilder.append(lhour).append("小时");
        }
        if(lday == 0 && lhour==0){
            if(lminute > 0){
                sBuilder.append(lminute).append("分钟");
            }else {
                sBuilder.append("即将结束");
            }
        }
        return sBuilder.toString();
    }
    /**
     * 计算剩余时间
     * @param startDateStr
     * @param endDateStr
     * @return
     */
    public static String remainDateToString(String startDateStr, String endDateStr){
        Date startDate = null;
        Date endDate= null;
        try {
            startDate = new SimpleDateFormat("yyyy-MM-dd").parse(startDateStr);
        } catch (ParseException e) {
            e.printStackTrace();
            return "";
        }
        try {
            endDate = new SimpleDateFormat("yyyy-MM-dd").parse(endDateStr);
        } catch (ParseException e) {
            e.printStackTrace();
            return "";
        }
        
        calS.setTime(startDate);
        int startY = calS.get(Calendar.YEAR);
        int startM = calS.get(Calendar.MONTH);
        int startD = calS.get(Calendar.DATE);
        int startDayOfMonth = calS.getActualMaximum(Calendar.DAY_OF_MONTH);
        
        calS.setTime(endDate);
        int endY = calS.get(Calendar.YEAR);
        int endM = calS.get(Calendar.MONTH);
        //处理2011-01-10到2011-01-10，认为服务为一天
        int endD = calS.get(Calendar.DATE)+1;
        int endDayOfMonth = calS.getActualMaximum(Calendar.DAY_OF_MONTH);
        
        StringBuilder sBuilder = new StringBuilder();
        if (endDate.compareTo(startDate)<0) {
            return sBuilder.append("过期").toString();
        }
        int lday = endD-startD;
        if (lday<0) {
            endM = endM -1;
            lday = startDayOfMonth+ lday;
        }
        //处理天数问题，如：2011-01-01 到 2013-12-31  2年11个月31天     实际上就是3年
        if (lday == endDayOfMonth) {
            endM = endM+1;
            lday =0;
        }
        int mos = (endY - startY)*12 + (endM- startM);
        int lyear = mos/12;
        int lmonth = mos%12;
        if (lyear >0) {
            sBuilder.append(lyear+"年");
        }
        if (lmonth > 0) {
            sBuilder.append(lmonth+"个月");
        }
        if (lday >0 ) {
            sBuilder.append(lday+"天");
        }
        return sBuilder.toString();
    }
    
    /**
     * 计算剩余天数
     * @param startTime
     * @param endTime
     * @return
     */
    public static int remainDay(long startTime, long endTime){
         long delayTime = endTime - startTime;
         if(delayTime <= 0){//已过期
        	 return -1;
         }
         int day = (int)(delayTime / DAY_TIME);
         if(delayTime % DAY_TIME != 0){
        	 day += 1;
         }
         
         return day;
    }
    
    /**
     * 计算有效剩余天数
     * @param validtime
     * @return
     */
    public static int remainValidDay(long validtime){
    	return remainDay(System.currentTimeMillis(), validtime);
    }
}
